import { http, HTTP_200, HTTP_201, HTTP_204 } from '@/store/api'

const state = {
  tagItems: [],
  http_status: 0,
  http_msg: ''
}

const getters = {
}

const mutations = {
  createTagItem (state, payload) {
    state.tagItems.push(payload)
  },
  fetchTagItems (state, payload) {
    state.tagItems = payload
  },
  updateTagItem (state, payload) {
    state.tagItems = state.tagItems.map(item => {
      if (item.id === payload.id) {
        item.tag_name = payload.tag_name
      }
      return item
    })
  },
  removeTagItem (state, payload) {
    const old = state.tagItems.filter(item => item.id !== payload)
    state.tagItems = old
  },
  setHTTPMessage (state, payload) {
    state.http_status = payload.status
    state.http_msg = payload.msg
  },
  restHTTPMessage (state) {
    state.http_status = 0
    state.http_msg = ''
  }
}

const actions = {
  fetchTagItems ({commit}) {
    http.get(`/tags/`).then(res => {
      if (res.status === HTTP_200) {
        commit('fetchTagItems', res.data)
      }
    }).catch(err => {
      commit('setHTTPMessage', {status: err.status, msg: err.message})
    })
  },
  updateTagItem ({commit}, payload) {
    http.put(`/tags/${payload.id}/`, payload).then(res => {
      if (res.status === HTTP_200) {
        commit('updateTagItem', res.data)
      }
    }).catch(err => {
      commit('setHTTPMessage', {status: err.status, msg: err.message})
    })
  },
  createTagItem ({commit}, payload) {
    http.post(`/tags/`, payload).then(res => {
      if (res.status === HTTP_201) {
        commit('createTagItem', res.data)
      }
    }).catch(err => {
      commit('setHTTPMessage', {status: err.response.status, msg: `${err.message}: ${err.response.statusText}`})
    })
  },
  removeTagItem ({commit}, payload) {
    http.delete(`/tags/${payload}/`).then(res => {
      if (res.status === HTTP_204) {
        commit('removeTagItem', payload)
      }
    }).catch(err => {
      commit('setHTTPMessage', {status: err.status, msg: err.message})
    })
  }
}

export default {
  state,
  getters,
  mutations,
  actions
}
